package com.hjf.list;

public class Test {
    public static void main(String[] args) {
//        ListNode list = new ListNode();
        int[] nums = {7,7,7};
        int val = 7;
        ListNode head = initNode(nums);
        printList(head);
        head = removeElements(head, val);
        printList(head);
    }

    public static ListNode removeElements(ListNode head, int val){

        while(head != null && head.val == val){
            head = head.next;
        }

        if(head == null){
            return null;
        }

        ListNode current = head;
        while(current.next != null){
            if(current.next.val == val){
                current.next = current.next.next;
            }
            else {
                current = current.next;
            }
        }

        return head;
    }

    public static ListNode removeElements2(ListNode head, int val){ //设置虚拟头节点
        ListNode dummy = new ListNode();
        dummy.next = head;

        ListNode current = dummy;
        while(current.next != null){
            if(current.next.val == val){
                current.next = current.next.next;
            }else{
                current = current.next;
            }
        }
        return dummy.next;
    }

    public static ListNode initNode(int[] nums){
       if(nums == null || nums.length == 0) {
           return null;
       }

       ListNode head = new ListNode(nums[0]);
       head.next = null;
       ListNode current = head;

        for (int i = 1; i < nums.length; i++) {
            current.next = new ListNode(nums[i]);
            current = current.next;
        }

        return head;
    }

    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }
}
